package com.reagent.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @Description: 代码生成工具类(配合mybatis - plus使用)
 * @ClassNmae: CodeGeneratorUtils
 * @Author: HeYue
 * @DateTime: 2020-11-14 17:26
 **/
public class CodeGeneratorUtils {

    /*数据库类型*/
    private static final DbType dbType = DbType.MYSQL;

    /*数据库连结信息*/
    private static final String dbUrl = "jdbc:mysql://localhost:3306/reagent?useUnicode=true&characterEncoding=UTF-8" +
            "&serverTimezone=GMT%2B8";
    private static final String dbDriverName = "com.mysql.cj.jdbc.Driver";
    private static final String dbUserName = "root";
    private static final String dbPassword = "123456";

    /*全局配置*/
    //设置作者
    private static final String gcAuthor = "Heyue";
    //设置文件目录
    private static final String gcPath = "/src/main/java";
    //是否打开资源管理器
    private static final boolean gcOpen = false;
    //是否自动覆盖文件(重新生成时)*/
    private static final boolean gcFileOverride = true;
    //设置自动生成的Service接口名称
    private static final String gcServiceName = "%sService";
    //设置自动生成的ServiceImpl实现类名称
    private static final String gcServiceImplName = "%sServiceImpl";
    //设置主键生成策略(自增)
    private static final IdType gcIdType = IdType.AUTO;
    //设置Date数据类型
    private static final DateType gcDateType = DateType.ONLY_DATE;
    //开启Swagger2注解
    private static final boolean gcSwagger2 = true;

    /*包配置*/
    //设置父级目录
    private static final String gcParent = "com.reagent";
    //设置Controller目录
    private static final String gcController = "controller";
    //设置Entity目录
    private static final String gcEntity = "entity";
    //设置Mapper目录
    private static final String gcMapper = "mapper";
    //设置Service目录
    private static final String gcService = "service";
    //设置ServiceImpl目录
    private static final String gcServiceImpl = "service.impl";

    //设置使用的模板引擎  velocity:/templates/mapper.xml.vm    freemarker:/templates/mapper.xml.ftl
    private static final String tePath = "/templates/mapper.xml.vm";
    //设置Mapper.xml目录
    private static final String mapperPath = "/src/main/resources/mapper/";

    /*策略配置*/
    //开启驼峰命名(实体类)
    private static final NamingStrategy stNaming = NamingStrategy.underline_to_camel;
    //开启驼峰命名(列)
    private static final NamingStrategy stColumnNaming = NamingStrategy.underline_to_camel;
    //开启使用Lombok
    private static final boolean stEntityLombokModel = true;
    //设置controller API风格 Result风格
    private static final boolean stRestControllerStyle = true;
    //设置控制器连接符样式
    private static final boolean stControllerMappingHyphenStyle = true;


    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        GlobalConfig gc = new GlobalConfig();
        DataSourceConfig dsc = new DataSourceConfig();
        PackageConfig pc = new PackageConfig();
        StrategyConfig strategy = new StrategyConfig();
        String path = scanner("请输入项目路径");
        //全局配置
        gc.setOutputDir(path + gcPath)
                .setAuthor(gcAuthor)
                .setOpen(gcOpen)
                .setFileOverride(gcFileOverride)
                .setServiceName(gcServiceName)
                .setServiceImplName(gcServiceImplName)
                .setIdType(gcIdType)
                .setDateType(gcDateType)
                .setSwagger2(gcSwagger2);
        mpg.setGlobalConfig(gc);
        //设置数据库
        dsc.setUrl(dbUrl)
                .setDriverName(dbDriverName)
                .setUsername(dbUserName)
                .setPassword(dbPassword)
                .setDbType(dbType);
        mpg.setDataSource(dsc);
        //设置模块
        pc.setModuleName(scanner("请输入模块名"))
                .setParent(gcParent)
                .setController(gcController)
                .setService(gcService)
                .setServiceImpl(gcServiceImpl)
                .setMapper(gcMapper)
                .setEntity(gcEntity);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        String templatePath = tePath;
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return path + mapperPath + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录，自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在，不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });*/

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        strategy.setInclude(scanner("输入需要自动生成表名(以英文逗号分割)").split(","))
                .setNaming(stNaming)
                .setColumnNaming(stColumnNaming)
                .setEntityLombokModel(stEntityLombokModel)
                .setRestControllerStyle(stRestControllerStyle)
                .setControllerMappingHyphenStyle(stControllerMappingHyphenStyle);
        /*驼峰转连接符*/
        //strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new VelocityTemplateEngine());
        mpg.execute();
    }

}
